/*
 * @Author: huangyq
 * @Date: 2022/3/31 下午2:47
 * @Last Modified by: huangyq
 * @Last Modified time: 2022/3/31 下午2:47
 * @Desc
 */
import { App } from 'vue'
import {
  createRouter,
  createWebHistory,
  NavigationGuardNext,
  RouteLocationNormalized
} from 'vue-router'
import routes from './routes'
import { usePermissionStore } from '@/stores'
import { removeStorage, clearStorage } from '@/utils'
import { ElMessage } from 'element-plus'

const router = createRouter({
  history: createWebHistory(),
  routes: routes
})
router.beforeEach(
  async (
    to: RouteLocationNormalized,
    form: RouteLocationNormalized,
    next: NavigationGuardNext
  ) => {
    const isLogin = to.name === 'login'
    const hasToken = !!sessionStorage.getItem('token')
    if (isLogin) {
      if (hasToken) removeStorage('token')
      next()
    } else {
      if (!hasToken) {
        next('/login')
      } else {
        // 获取权限
        const permissionStore = usePermissionStore()
        if (permissionStore.codes.length === 0) {
          await permissionStore.fetchPermission()
          if (permissionStore.codes.length === 0) {
            ElMessage.error('没有访问权限')
            setTimeout(() => {
              clearStorage()
            }, 1500)
          }
        }
        if (!to.name) {
          // 没有路由
          next('/error404')
        } else if (
          // 没有权限
          !to.meta?.code ||
          !permissionStore.checkPermissionByCode(to.meta?.code as string)
        ) {
          next('/error403')
        } else {
          next()
        }
      }
    }
  }
)

export default function useRouters(app: App) {
  app.use(router)
}
